package com.bootdo.system.filter;

import com.alibaba.fastjson.JSON;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.sso.LoadUserInfoImp;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.apache.shiro.web.servlet.AdviceFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


public class ShiroCheckTokenFilter extends AdviceFilter {
    LoadUserInfoImp loadUserInfoImp;

    public ShiroCheckTokenFilter(LoadUserInfoImp loadUserInfoImp){
        this.loadUserInfoImp = loadUserInfoImp;
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String ssoToken =  req.getParameter("sso_token");
        if(StringUtils.isEmpty(ssoToken)){
            ssoToken = req.getHeader("sso_token");
        }
        if(StringUtils.isNotEmpty(ssoToken)){
            loadUserInfoImp.checkToken(ssoToken);
        }
        Subject subject = SecurityUtils.getSubject();
        if(subject.isAuthenticated()){
            return true;
        }else{
           /* if (StringUtils.isNotEmpty(ssoToken)) {

            }else{
                req.getRequestDispatcher("/login").forward(request, response);
            }*/
            staticWriteJson(req,res, R.error(401, "验证失败"));
            return false;
        }
    }


    private static void staticWriteJson( HttpServletRequest request, HttpServletResponse response,Object object){
        response.setContentType("application/json; charset=UTF-8");
        try {
            PrintWriter out = response.getWriter();
            String jsonString = JSON.toJSON(object).toString();
            out.print(jsonString);
            out.flush();
            out.close();
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

}
